package com.founder.bdyx.listener;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.founder.bdyx.core.util.DictionaryCache;
import com.founder.bdyx.modules.sys.mapper.CommonDictMapper;
import com.founder.bdyx.modules.sys.model.CommonDict;
import com.founder.bdyx.wxpro.conf.WxConfig;
import com.founder.bdyx.wxpro.util.HttpUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;
import org.springframework.web.context.WebApplicationContext;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.ServletContext;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 */
@Component
public class SettingDataInitListener implements ApplicationListener<ContextRefreshedEvent> {

    @Autowired
    private WxConfig wxConfig;
    @Autowired
    private CommonDictMapper dictMapper;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        //需要执行的逻辑代码，当spring容器初始化完成后就会执行该方法
        // 防止父子容器多次执行
        if(contextRefreshedEvent.getApplicationContext().getParent() == null){
            // 将 ApplicationContext 转化为 WebApplicationContext
            /*WebApplicationContext webApplicationContext =
                    (WebApplicationContext)contextRefreshedEvent.getApplicationContext();
            // 从 webApplicationContext 中获取  servletContext
            ServletContext servletContext = webApplicationContext.getServletContext();
            String accessToken = (String) servletContext.getAttribute("access_token");
            if(accessToken != null) return ;*/

            Example example=new Example(CommonDict.class);
            List<CommonDict> al = dictMapper.selectByExample(example);

            Map<String, Map<String, String>> mapDict = new HashMap<>();
            for (CommonDict dict : al){
                if(mapDict.containsKey(dict.getCname())){
                    Map<String,String> mapDetail = mapDict.get(dict.getCname());
                    mapDetail.put(String.valueOf(dict.getCkey()),dict.getCval());
                    continue;
                }
                Map<String,String> mapDetailNew = new HashMap<>();
                mapDetailNew.put(String.valueOf(dict.getCkey()),dict.getCval());

                mapDict.put(dict.getCname(),mapDetailNew);
            }

            DictionaryCache.dictMap = mapDict;
        }
    }
}
